package com.mxpio.erp.equipment.service.impl;

import com.mxpio.erp.common.equipment.entity.EquipmentEqpBasics;
import com.mxpio.erp.common.equipment.entity.EquipmentEqpStatusRecords;
import com.mxpio.erp.common.equipment.service.EquipmentEqpStatusRecordsService;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 设备状态Service业务层处理
 *
 * @author Cheng
 * @date 2023-07-01
 */
@Service
public class EquipmentEqpStatusRecordsServiceImpl extends BaseServiceImpl<EquipmentEqpStatusRecords> implements EquipmentEqpStatusRecordsService {

    @Autowired
    private EquipmentEqpStatusRecordsService equipmentEqpStatusRecordsService;

    @Override
    @Transactional(readOnly = false)
    public void saveRecordAndUpdatePreRecord(EquipmentEqpBasics eqpBasics, Integer nowStatus, String reason) {

        Criteria criteria = Criteria.create().addCriterion("basicsCode", Operator.EQ, eqpBasics.getBasicsCode());
        //更新上一条记录的下一个操作时间
        List<EquipmentEqpStatusRecords> eqpStatusRecords = equipmentEqpStatusRecordsService.list(EquipmentEqpStatusRecords.class,criteria);
        if (eqpStatusRecords.size() > 0) {
            EquipmentEqpStatusRecords statusRecord = eqpStatusRecords.get(eqpStatusRecords.size() - 1);
            statusRecord.setNextOperateTime(new Date());
            equipmentEqpStatusRecordsService.update(statusRecord);
        }

        //添加状态变更记录
        EquipmentEqpStatusRecords statusRecords = new EquipmentEqpStatusRecords();
        statusRecords.setBasicsCode(eqpBasics.getBasicsCode());
        statusRecords.setIsDel(0);
        statusRecords.setNowStatus(nowStatus);
        statusRecords.setBeforeStatus(eqpBasics.getStatus());
        statusRecords.setReason(reason);
        equipmentEqpStatusRecordsService.save(statusRecords);
    }
}
